from geocoder import ip
from geocoder.ipinfo import IpinfoQuery
from requests import get
from datetime import (
    datetime,
    timedelta
)
from typing import Optional
from rich.table import Table
from rich.console import Console
from utils import (
    config,
    WeatherHistory,
    Unit, Language,
    get_location,
    format_time
)
from utils.type import (
    _WeatherHistoryDaily,
    _WeatherHistoryHourly
)

_yesterday = datetime.now() - timedelta(days=1)
yesterday = _yesterday.strftime('%Y%m%d')

def weather_history(
        location: Optional[str]=None,
        date: str=yesterday,
        language: Language=None,
        unit: Unit=None
    ) -> tuple[_WeatherHistoryDaily, list[_WeatherHistoryHourly]]:
    """
    Get weather history

    Args:
        location: Location to get weather history. Default: `None`
        date: Date to get weather history. Default: yesterday, format: `YYYYMMDD`
        language: Language to get weather history. Default: `None`
        unit: Unit to get weather history. Default: `None`
    """
    # Get location
    if location is None:
        location = 'me'
        g: IpinfoQuery = ip(location, timeout=1)
        loc = g.adcode
    else:
        loc = get_location(location, type='id')
    # Get language and unit
    if language is None:
        language = config.language
    if unit is None:
        unit = config.unit
    # Get qweather api
    base_url = f'{config.base_url}/v7/historical/weather?location={loc}&date={date}&lang={language}&unit={unit}'
    headers = {'Authorization': f'Bearer {config.token}'}
    # Send request and get response in json format
    resp = get(url=base_url, headers=headers)
    result: WeatherHistory = resp.json()
    if 'weatherDaily' in result and 'weatherHourly' in result:
        return result['weatherDaily'], result['weatherHourly']

def print_history(
        daily: _WeatherHistoryDaily,
        hourly: list[_WeatherHistoryHourly],
        unit: Unit=None
    ) -> None:
    """
    Print weather history

    Args:
        daily: Weather history daily
        hourly: Weather history hourly
        unit: Unit to print weather history. Default: `None`
    """
    # Get default unit
    if unit is None:
        unit = config.unit
    # Create Console
    console = Console()
    temp_unit = '°C' if unit == 'm' else '°F'
    # Create table for daily history
    daily_t = Table(title='🌤️ Weather daily history', header_style='bold magenta')
    daily_t.add_column('日期', style='cyan', justify='center')
    daily_t.add_column('日出日落时间', style='bold green', justify='center')
    daily_t.add_column('月出月落时间', style='bold green', justify='center')
    daily_t.add_column('温度', justify='center')
    # Add rows to table
    temp_min = f'[bold green]{daily["tempMin"]}{temp_unit}[/]'
    temp_max = f'[bold yellow]{daily["tempMax"]}{temp_unit}[/]'
    sunrise_and_sunset = f'{daily["sunrise"]}~{daily["sunset"]}'
    moonrise_and_moonset = f'{daily["moonrise"]}~{daily["moonset"]}'
    daily_t.add_row(
        format_time(daily['date'], '%Y/%m/%d'),
        sunrise_and_sunset,
        moonrise_and_moonset,
        f'{temp_min}~{temp_max}'
    )
    # Print daily table
    console.print(daily_t)
    console.print()
    # Create table for hourly history
    hourly_t = Table(title=f'🌤️ Weather 24 hours history', header_style='bold magenta')
    hourly_t.add_column('时间', style='cyan', justify='center')
    hourly_t.add_column('温度', justify='center')
    hourly_t.add_column('天气', style='blue', justify='center')
    hourly_t.add_column('风向风速', style='bold white', justify='left')
    hourly_t.add_column('风速', style='bold white', justify='center')
    # Add rows to table
    for hour in hourly:
        # Get temp color
        temp_color = 'red' if int(hour['temp']) >= 30 else \
            'yellow' if int(hour['temp']) >= 25 else 'green'
        hourly_t.add_row(
            format_time(hour['time'], '%Y/%m/%d %H:%M'),
            f'[bold {temp_color}]{hour["temp"]}{temp_unit}[/]',
            hour['text'],
            f'{hour["windDir"]} {hour["windScale"]}级',
            f'{hour["windSpeed"]}km/h'
        )
    # Print hourly table
    console.print(hourly_t)
